//
//  ViewController.m
//  代码约束播放界面
//
//  Created by dllo on 16/8/18.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "PlayToolBar.h"
#import "Masonry.h"
#import "UIImage+Common.h"

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UIView *shadowView;

@property (nonatomic, strong) UILabel *topNameLabel;

@property (nonatomic, strong) UIImageView *mainImageView;
@property (nonatomic, strong) UILabel *songWordLabel;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UIButton *frontSongBtn;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) UIButton *behindSongBtn;
@property (nonatomic, strong) PlayToolBar *toorBar;

@property (nonatomic, strong) UILabel *currentTimeLabel;
@property (nonatomic, strong) UILabel *maxTimeLabel;

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, assign) NSTimer *timer;

@property (nonatomic, strong) NSMutableArray *songWordArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    [self createSubviews];
    [self layoutSubviewsByMasonry];
    
}

- (void)handleData
{
    _songWordArray = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"稻香" ofType:@"lrc"];
    NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSArray *array = [string componentsSeparatedByString:@"\n"];
    for (NSString *str in array) {
        NSArray *arr = [str componentsSeparatedByString:@"] "];
        NSString *strOne = arr[0];
        strOne = [strOne substringFromIndex:1];
        strOne = [strOne substringToIndex:5];
        [_songWordArray addObject:strOne];
        [_songWordArray addObject:arr[1]];
    }
    
}

- (void)createSubviews
{
    _backImageView = [UIImageView new];
    [self.view addSubview:_backImageView];
    _backImageView.image = [UIImage imageNamed:@"player_albumblur_default"];
    
    _shadowView = [UIView new];
    [self.view addSubview:_shadowView];
    _shadowView.backgroundColor = [UIColor blackColor];
    _shadowView.alpha = 0.3;
    
    
    _topNameLabel = [UILabel new];
    [self.view addSubview:_topNameLabel];
    _topNameLabel.text = @"—— 周杰伦 ——";
    _topNameLabel.font = [UIFont systemFontOfSize:15];
    _topNameLabel.textColor = [UIColor whiteColor];
    
    _mainImageView = [UIImageView new];
    [self.view addSubview:_mainImageView];
    _mainImageView.layer.masksToBounds = YES;
    _mainImageView.image = [UIImage imageNamed:@"song"];
    
    
    _songWordLabel = [UILabel new];
    _songWordLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_songWordLabel];
    _songWordLabel.font = [UIFont systemFontOfSize:13];

    
    
    _pageControl = [UIPageControl new];
    [self.view addSubview:_pageControl];
    _pageControl.numberOfPages = 3;
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    
    _slider = [UISlider new];
    [self.view addSubview:_slider];
    _slider.tintColor = [UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1];
    _slider.thumbTintColor = [UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1];
    [_slider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [_slider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateHighlighted];
    _slider.minimumValue = 0;
    _slider.maximumValue = 1;
    _slider.value = 0;
    [_slider addTarget:self action:@selector(sliderSwipChangeValue) forControlEvents:UIControlEventTouchUpInside];
    [_slider addTarget:self action:@selector(sliderTouchBegin) forControlEvents:UIControlEventTouchDown];
    
    _currentTimeLabel = [UILabel new];
    [self.view addSubview:_currentTimeLabel];
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [UIFont systemFontOfSize:12];
    _currentTimeLabel.text = @"00:00";
    
    _maxTimeLabel = [UILabel new];
    [self.view addSubview:_maxTimeLabel];
    _maxTimeLabel.textColor = [UIColor whiteColor];
    _maxTimeLabel.font = [UIFont systemFontOfSize:12];
    
    _frontSongBtn = [UIButton new];
    [self.view addSubview:_frontSongBtn];
    [_frontSongBtn setBackgroundImage:[UIImage imageNamed:@"front"] forState:UIControlStateNormal];
    
    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_playBtn];
    [_playBtn setBackgroundImage:[[UIImage imageNamed:@"play"] imageWithColor:[UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1]] forState:UIControlStateNormal];
    _playBtn.tag = 100;
    [_playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _behindSongBtn = [UIButton new];
    [self.view addSubview:_behindSongBtn];
    [_behindSongBtn setBackgroundImage:[UIImage imageNamed:@"behind"] forState:UIControlStateNormal];
    
    _toorBar = [PlayToolBar new];
    [self.view addSubview:_toorBar];
    _toorBar.backgroundColor = [UIColor clearColor];
    
    
}

#pragma mark - button slider click
- (void)playAction:(UIButton *)sender
{
    if (sender.tag == 100) {
        [sender setBackgroundImage:[[UIImage imageNamed:@"mymusic_guess_like_pause"] imageWithColor:[UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1]] forState:UIControlStateNormal];
        [self play];
        sender.tag = 200;
    } else {
        [sender setBackgroundImage:[[UIImage imageNamed:@"play"] imageWithColor:[UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1]] forState:UIControlStateNormal];
        [self pause];
        sender.tag = 100;
    }
}

/** slider 的点击开始 */
- (void)sliderTouchBegin
{
    if ([self.audioPlayer isPlaying]) {
        _timer.fireDate = [NSDate distantFuture];
    }
}
/** slider 的点击结束 */
- (void)sliderSwipChangeValue
{
    if ([self.audioPlayer isPlaying]) {
        _audioPlayer.currentTime = _slider.value;
        _timer.fireDate = [NSDate distantPast];
    } else {
        [_slider setValue:0 animated:YES];
    }
}

#pragma mark - 定时器(懒加载)
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)updateProgress
{
    CGFloat progress = _audioPlayer.currentTime / _audioPlayer.duration;
    _currentTimeLabel.text = [self timeFormatted:self.audioPlayer.currentTime];
    [_slider setValue:progress * _slider.maximumValue animated:YES];
    NSInteger index = [_songWordArray indexOfObject:_currentTimeLabel.text];
    if (index >= 0 && index < _songWordArray.count) {
        _songWordLabel.text = _songWordArray[index + 1];
    }
}


#pragma mark - 播放器
/** audioPlayer 创建(懒加载) */
- (AVAudioPlayer *)audioPlayer
{
    if (!_audioPlayer) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"周杰伦 - 稻香" ofType:@"mp3"];
        NSURL *url = [NSURL fileURLWithPath:path];
        _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        _audioPlayer.delegate = self;
        
        _maxTimeLabel.text = [self timeFormatted:_audioPlayer.duration];
        _slider.maximumValue = _audioPlayer.duration;
        // 设置播放属性
        _audioPlayer.numberOfLoops = 0; // 不循环
        [_audioPlayer prepareToPlay]; // 准备播放，加载音频文件到缓存
        
    }
    return _audioPlayer;
}

- (NSString *)timeFormatted:(float)timeInterval
{
    int time = (int)timeInterval;
    int seconds = time % 60;
    int minutes = (time / 60) % 60;
    int hours = time / 3600;
    if (hours == 0) {
        return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

/** 播放 */
- (void)play
{
    if (![self.audioPlayer isPlaying]) {
        [self.audioPlayer play];
        self.timer.fireDate = [NSDate distantPast];//回复定时器
    }
}

- (void)pause
{
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer pause];
        self.timer.fireDate = [NSDate distantFuture];
    }
}

/** audioPlayer delegate */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [_playBtn setBackgroundImage:[[UIImage imageNamed:@"play"] imageWithColor:[UIColor colorWithRed:0.137 green:0.756 blue:0.49 alpha:1]] forState:UIControlStateNormal];
    [_timer finalize];
}

#pragma mark - 约束
- (void)layoutSubviewsByMasonry
{
    [_backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [_topNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(15 + 64);
    }];
    [_mainImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).multipliedBy(0.85);
        make.width.equalTo(self.view).multipliedBy(0.7);
        make.height.equalTo(_mainImageView.mas_width);
    }];
    [_shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_mainImageView);
        make.width.equalTo(self.view).multipliedBy(0.76);
        make.height.equalTo(_shadowView.mas_width);
    }];
    [_songWordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_mainImageView.mas_bottom).offset([UIScreen mainScreen].bounds.size.height / 30);
    }];
    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(_songWordLabel.mas_bottom).offset([UIScreen mainScreen].bounds.size.height / 40);
        make.height.mas_lessThanOrEqualTo(20);
    }];
    [_slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.equalTo(_playBtn.mas_top).offset(-1 * [UIScreen mainScreen].bounds.size.height / 50);
        make.width.equalTo(self.view).multipliedBy(0.7);
        make.height.mas_lessThanOrEqualTo(20);
    }];
    [_currentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_slider.mas_left).mas_offset(-5);
        make.centerY.equalTo(_slider);
    }];
    [_maxTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_slider.mas_right).mas_offset(5);
        make.centerY.equalTo(_slider);
    }];
    [_toorBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    [_playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_toorBar.mas_top).offset(-1 * [UIScreen mainScreen].bounds.size.height / 50);
        make.centerX.mas_equalTo(0);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.17);
        make.height.equalTo(_playBtn.mas_width);
    }];
    
    [_frontSongBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).multipliedBy(0.48);
        make.centerY.equalTo(_playBtn);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.12);
        make.height.equalTo(_frontSongBtn.mas_width);
    }];
    [_behindSongBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).multipliedBy(1.52);
        make.centerY.equalTo(_playBtn);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.12);
        make.height.equalTo(_behindSongBtn.mas_width);
    }];
    
    
}

- (void)viewDidLayoutSubviews
{
    _mainImageView.layer.cornerRadius = CGRectGetWidth(_mainImageView.frame) / 2;
    
    _shadowView.layer.cornerRadius = CGRectGetWidth(_shadowView.frame) / 2;
    
    _playBtn.layer.cornerRadius = CGRectGetWidth(_playBtn.frame) / 2;
    
    _frontSongBtn.layer.cornerRadius = CGRectGetWidth(_frontSongBtn.frame) / 2;
    
    _behindSongBtn.layer.cornerRadius = CGRectGetWidth(_behindSongBtn.frame) / 2;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
